package com.guardchina.framework.web.plugins.response;

import com.guardchina.framework.util.model.ResultHolder;
import com.google.gson.Gson;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 描述
 *
 * @author lwb
 * @since 2020/3/20
 */
@RestControllerAdvice(basePackages = "com.property")
public class ResultHolderResponseAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if(o instanceof ResultHolder){
            return o;
        }

        if(o instanceof String){
            return new Gson().toJson(ResultHolder.success(o));
        }

        return ResultHolder.success(o);
    }
}
